<template>
  <div class="product-list-page">
    <!-- 搜索结果提示 -->
    <div class="search-result-info bg-light py-3" v-if="searchKeyword">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <p class="mb-0">
              <i class="fas fa-search me-2"></i>
              搜索关键词："<strong>{{ searchKeyword }}</strong>"，共找到 
              <span class="text-primary fw-bold">{{ totalProducts }}</span> 件商品
            </p>
          </div>
        </div>
      </div>
    </div>

    <div class="container py-4">
      <div class="row">
        <!-- 左侧筛选栏 -->
        <div class="col-lg-3 d-none d-lg-block">
          <div class="filter-sidebar">
            <!-- 品牌筛选 -->
            <div class="filter-section mb-4">
              <h5 class="filter-title">品牌</h5>
              <div class="filter-content">
                <div class="form-check mb-2" v-for="brand in brands" :key="brand.value">
                  <input 
                    class="form-check-input" 
                    type="checkbox" 
                    :id="'brand-' + brand.value"
                    :value="brand.value" 
                    v-model="filters.brands"
                    @change="applyFilters"
                  >
                  <label class="form-check-label" :for="'brand-' + brand.value">
                    {{ brand.label }}
                    <span class="text-muted ms-1">({{ brand.count }})</span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 清空筛选 -->
            <div class="filter-actions">
              <button class="btn btn-outline-secondary btn-sm" @click="clearFilters">
                <i class="fas fa-times me-1"></i>
                清空筛选
              </button>
            </div>
          </div>
        </div>

        <!-- 右侧商品列表 -->
        <div class="col-lg-9">
          <!-- 工具栏 -->
          <div class="product-toolbar d-flex justify-content-between align-items-center mb-4">
            <div class="toolbar-left d-flex align-items-center">
              <span class="text-muted me-3">共 {{ totalProducts }} 件商品</span>
              
              <!-- 移动端筛选按钮 -->
              <button 
                class="btn btn-outline-primary btn-sm d-lg-none me-3"
                @click="showMobileFilters = true"
              >
                <i class="fas fa-filter me-1"></i>
                筛选
              </button>
            </div>
            
            <div class="toolbar-right d-flex align-items-center">
              <!-- 视图切换 -->
              <div class="btn-group me-3" role="group">
                <input type="radio" class="btn-check" id="grid-view" v-model="viewMode" value="grid">
                <label class="btn btn-outline-secondary btn-sm" for="grid-view">
                  <i class="fas fa-th"></i>
                </label>
                
                <input type="radio" class="btn-check" id="list-view" v-model="viewMode" value="list">
                <label class="btn btn-outline-secondary btn-sm" for="list-view">
                  <i class="fas fa-list"></i>
                </label>
              </div>
              
              <!-- 排序 -->
              <select class="form-select form-select-sm" v-model="sortBy" @change="applySort">
                <option value="">默认排序</option>
                <option value="price-asc">价格从低到高</option>
                <option value="price-desc">价格从高到低</option>
                <option value="sales-desc">销量从高到低</option>
                <option value="rating-desc">好评度从高到低</option>
                <option value="newest">最新上架</option>
              </select>
            </div>
          </div>

          <!-- 商品网格视图 -->
          <div v-if="viewMode === 'grid'" class="product-grid">
            <div class="row" v-if="!loading && products.length > 0">
              <div 
                class="col-6 col-md-4 col-xl-3 mb-4" 
                v-for="product in products" 
                :key="product.id"
              >
                <div class="product-card card h-100">
                  <div class="product-image-wrapper">
                    <img 
                      :src="placeholderImage(300, 300)"
                      :alt="product.name" 
                      class="product-image card-img-top"
                    />
                    <div class="product-actions">
                      <button class="btn btn-sm btn-primary" @click="addToCart(product)">
                        <i class="fas fa-shopping-cart"></i>
                      </button>

                      <button class="btn btn-sm btn-outline-secondary" @click="quickView(product)">
                        <i class="fas fa-eye"></i>
                      </button>
                    </div>

                  </div>
                  
                  <div class="card-body d-flex flex-column">
                    <h6 class="product-name mb-2">
                      <router-link :to="`/products/${product.id}`" class="text-decoration-none">
                        {{ product.name }}
                      </router-link>
                    </h6>
                    <p class="product-description text-muted small mb-2">
                      {{ product.description }}
                    </p>
                    <div class="product-status mb-2">
                      <span v-if="product.isHot" class="badge bg-danger me-1">热门</span>
                      <span v-if="product.stock <= 10 && product.stock > 0" class="badge bg-warning me-1">库存紧张</span>
                      <span v-if="product.stock === 0" class="badge bg-secondary">缺货</span>
                    </div>
                    <div class="product-price mt-auto">
                      <span class="current-price text-danger fw-bold">
                        {{ formatPrice(product.price) }}
                      </span>
                      <span v-if="product.marketPrice && product.marketPrice > product.price" class="original-price text-muted text-decoration-line-through ms-2">
                        {{ formatPrice(product.marketPrice!) }}
                      </span>
                    </div>
                    <div class="product-sales text-muted small">
                      已售 {{ product.salesCount || 0 }} 件
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 商品列表视图 -->
          <div v-if="viewMode === 'list'" class="product-list">
            <div class="product-list-item card mb-3" v-for="product in products" :key="product.id">
              <div class="row g-0">
                <div class="col-md-3">
                  <div class="product-image-wrapper">
                    <img 
                      :src="placeholderImage(200, 200)"
                      :alt="product.name" 
                      class="product-image img-fluid"
                    />
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="card-body">
                    <h5 class="product-name">
                      <router-link :to="`/products/${product.id}`" class="text-decoration-none">
                        {{ product.name }}
                      </router-link>
                    </h5>
                    <p class="product-description text-muted">{{ product.description }}</p>
                    <div class="product-tags mb-2">
                      <span v-if="product.isHot" class="badge bg-danger me-1">热门</span>
                      <span v-if="product.stock <= 10 && product.stock > 0" class="badge bg-warning me-1">库存紧张</span>
                      <span v-if="product.stock === 0" class="badge bg-secondary me-1">缺货</span>
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="card-body text-center">
                    <div class="product-price mb-3">
                      <div class="current-price text-danger fw-bold h5">
                        {{ formatPrice(product.price) }}
                      </div>
                      <div v-if="product.marketPrice && product.marketPrice > product.price" class="original-price text-muted text-decoration-line-through">
                        {{ formatPrice(product.marketPrice!) }}
                      </div>
                    </div>
                    <div class="product-sales text-muted small mb-3">
                      已售 {{ product.salesCount || 0 }} 件
                    </div>
                    <div class="product-actions">
                      <button class="btn btn-primary btn-sm mb-2 w-100" @click="addToCart(product)">
                        <i class="fas fa-shopping-cart me-1"></i>
                        加入购物车
                      </button>

                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载中 -->
          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
            <div class="mt-2">加载中...</div>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && products.length === 0" class="empty-state text-center py-5">
            <i class="fas fa-search fa-4x text-muted mb-3"></i>
            <h4>没有找到相关商品</h4>
            <p class="text-muted">尝试调整搜索条件或筛选条件</p>
            <button class="btn btn-primary" @click="clearFilters">
              清空筛选条件
            </button>
          </div>

          <!-- 分页 -->
          <div class="pagination-wrapper mt-5" v-if="!loading && products.length > 0">
            <nav aria-label="商品分页">
              <ul class="pagination justify-content-center">
                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                  <button class="page-link" @click="changePage(currentPage - 1)" :disabled="currentPage === 1">
                    <i class="fas fa-chevron-left"></i>
                  </button>
                </li>
                <li 
                  class="page-item" 
                  :class="{ active: n === currentPage }"
                  v-for="n in totalPages" 
                  :key="n"
                  v-show="Math.abs(n - currentPage) <= 2 || n === 1 || n === totalPages"
                >
                  <button class="page-link" @click="changePage(n)">{{ n }}</button>
                </li>
                <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                  <button class="page-link" @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages">
                    <i class="fas fa-chevron-right"></i>
                  </button>
                </li>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>

    <!-- 移动端筛选弹窗 -->
    <div 
      class="mobile-filter-overlay d-lg-none" 
      :class="{ show: showMobileFilters }"
      @click="showMobileFilters = false"
    >
      <div class="mobile-filter-sidebar" @click.stop>
        <div class="filter-header d-flex justify-content-between align-items-center p-3">
          <h5 class="mb-0">筛选条件</h5>
          <button class="btn-close" @click="showMobileFilters = false"></button>
        </div>
        <div class="filter-body p-3">
          <!-- 移动端筛选内容与桌面端相同 -->
          <!-- 这里可以复制桌面端的筛选内容 -->
        </div>
        <div class="filter-footer p-3">
          <button class="btn btn-primary w-100" @click="applyFilters(); showMobileFilters = false">
            应用筛选
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { Message } from '@/utils/message'

// 导入真实的API
import { getProductList } from '@/api/product'
import { getBrandList } from '@/api/brand'
import { getCategoryTree } from '@/api/category'
import type { Product } from '@/types/product'
import type { Brand } from '@/types/brand'
import type { CategoryTreeDTO } from '@/types/category'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const cartStore = useCartStore()

// 占位符图片生成函数
const placeholderImage = (width: number, height: number) => {
  return `https://picsum.photos/${width}/${height}?random=${Math.floor(Math.random() * 1000)}`
}

// 页面状态
const loading = ref(false)
const viewMode = ref('grid')
const showMobileFilters = ref(false)

// 搜索和筛选
const searchKeyword = ref('')
const sortBy = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 筛选条件
const filters = reactive({
  category: '',
  brands: [] as string[],
  brandId: null as number | null
})



// 商品数据
const products = ref<Product[]>([])
const totalProducts = ref(0)

// 筛选选项数据
const categories = ref<Array<{value: string, label: string, count: number}>>([])
const brands = ref<Array<{value: string, label: string, count: number}>>([])



// 计算属性
const totalPages = computed(() => {
  return Math.ceil(totalProducts.value / pageSize.value)
})

// 格式化价格
const formatPrice = (price: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(price)
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getCategoryTree(1) // 只获取启用的分类
    const categoryOptions = [
      { value: '', label: '全部分类', count: 0 }
    ]
    
    // 递归处理分类树
    const processCategories = (cats: CategoryTreeDTO[], level = 0) => {
      cats.forEach(cat => {
        categoryOptions.push({
          value: cat.id.toString(),
          label: '　'.repeat(level) + cat.name,
          count: 0 // 商品数量需要从后端获取或计算
        })
        if (cat.children && cat.children.length > 0) {
          processCategories(cat.children, level + 1)
        }
      })
    }
    
    processCategories(response.data)
    categories.value = categoryOptions
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取品牌列表
const fetchBrands = async () => {
  try {
    const response = await getBrandList({
      status: 1, // 只获取启用的品牌
      page: 1,
      size: 100 // 获取足够多的品牌选项
    })
    
    brands.value = [
      { value: '', label: '全部品牌', count: 0 },
      ...response.data.records.map(brand => ({
        value: brand.id.toString(),
        label: brand.name,
        count: 0 // 品牌下的商品数量需要从后端获取或计算
      }))
    ]
  } catch (error) {
    console.error('获取品牌列表失败:', error)
  }
}

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true
  try {
    const queryParams: any = {
      page: currentPage.value,
      size: pageSize.value,
      status: 1 // 只获取上架商品
    }
    
    // 添加搜索关键词（包括空关键词，让后端决定如何处理）
    queryParams.keyword = searchKeyword.value || ''
    
    // 添加分类筛选
    if (filters.category) {
      queryParams.categoryId = parseInt(filters.category)
    }
    
    // 添加品牌筛选
    if (filters.brandId) {
      queryParams.brandId = filters.brandId
    }
    
    // 添加热门商品筛选
    if (sortBy.value === 'hot') {
      queryParams.isHot = 1
    }
    

    
    const response = await getProductList(queryParams)
    
    let productList = response.data.list
    
    // 前端排序处理
    if (sortBy.value && sortBy.value !== 'hot') {
      switch (sortBy.value) {
        case 'price-asc':
          productList.sort((a, b) => a.price - b.price)
          break
        case 'price-desc':
          productList.sort((a, b) => b.price - a.price)
          break
        case 'sales-desc':
          productList.sort((a, b) => (b.salesCount || 0) - (a.salesCount || 0))
          break
        case 'newest':
          productList.sort((a, b) => new Date(b.createdTime).getTime() - new Date(a.createdTime).getTime())
          break
      }
    }
    
    products.value = productList
    totalProducts.value = response.data.total
    
  } catch (error) {
    console.error('获取商品列表失败:', error)
    Message.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const applyFilters = () => {
  currentPage.value = 1
  fetchProducts()
}

const applySort = () => {
  fetchProducts()
}

const clearFilters = () => {
  filters.category = ''
  filters.brands = []
  filters.brandId = null
  sortBy.value = ''
  currentPage.value = 1
  fetchProducts()
}

const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    fetchProducts()
    // 滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

const addToCart = async (product: Product) => {
  if (!userStore.isLoggedIn) {
    Message.warning('请先登录')
    return
  }
  
  try {
    await cartStore.addToCart(product.id, 1)
    Message.success('已添加到购物车')
  } catch (error: any) {
    console.error('添加到购物车失败:', error)
    const errorMessage = error.message || '添加失败，请重试'
    Message.error(errorMessage)
  }
}



const quickView = (product: Product) => {
  router.push(`/products/${product.id}`)
}

// 处理品牌筛选变化
watch(() => filters.brands, (newBrands) => {
  // 如果选择了品牌，取第一个作为brandId
  filters.brandId = newBrands.length > 0 ? parseInt(newBrands[0]) : null
  applyFilters()
})

// 监听路由变化
watch(() => route.query, (newQuery) => {
  searchKeyword.value = (newQuery.keyword as string) || ''
  filters.category = (newQuery.categoryId as string) || ''
  filters.brandId = newQuery.brandId ? parseInt(newQuery.brandId as string) : null
  sortBy.value = (newQuery.sort as string) || ''
  fetchProducts()
}, { immediate: true })

onMounted(() => {
  // 初始化页面数据
  fetchCategories()
  fetchBrands()
  fetchProducts()
})
</script>

<style scoped>
/* 筛选侧边栏 */
.filter-sidebar {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 20px;
}

.filter-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e9ecef;
}

.filter-section {
  border-bottom: 1px solid #f8f9fa;
  padding-bottom: 15px;
}

.filter-section:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.form-check-label {
  font-size: 14px;
  cursor: pointer;
}

.price-range-custom {
  border-top: 1px solid #f8f9fa;
  padding-top: 15px;
}

/* 工具栏 */
.product-toolbar {
  background: white;
  padding: 15px 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.btn-check:checked + .btn {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

/* 商品卡片 - 网格视图 */
.product-card {
  border: none;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.product-image-wrapper {
  position: relative;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 220px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: opacity 0.3s ease;
  display: flex;
  gap: 10px;
}

.product-card:hover .product-actions {
  opacity: 1;
}

.product-actions .btn {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-badges {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-badges .badge {
  font-size: 10px;
  padding: 3px 6px;
}

.product-name {
  font-weight: 500;
  line-height: 1.3;
}

.product-name a {
  color: #333;
}

.product-name a:hover {
  color: #007bff;
}

.product-description {
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-rating .stars {
  display: inline-flex;
  font-size: 12px;
}

.product-price .current-price {
  font-size: 1.1rem;
}

.product-price .original-price {
  font-size: 0.9rem;
}

.product-sales {
  margin-top: 5px;
}

/* 商品卡片 - 列表视图 */
.product-list-item {
  border: none;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.product-list-item:hover {
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.product-list-item .product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 10px 0 0 10px;
}

.product-features .badge {
  font-size: 11px;
  margin-bottom: 5px;
}

/* 空状态 */
.empty-state {
  color: #6c757d;
}

/* 分页 */
.pagination .page-link {
  border-radius: 8px;
  margin: 0 3px;
  border: 1px solid #dee2e6;
  color: #007bff;
}

.pagination .page-item.active .page-link {
  background-color: #007bff;
  border-color: #007bff;
}

.pagination .page-link:hover {
  background-color: #f8f9fa;
  border-color: #007bff;
}

/* 移动端筛选 */
.mobile-filter-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1050;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
}

.mobile-filter-overlay.show {
  opacity: 1;
  visibility: visible;
}

.mobile-filter-sidebar {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 100%;
  background: white;
  transform: translateX(100%);
  transition: transform 0.3s ease;
  display: flex;
  flex-direction: column;
}

.mobile-filter-overlay.show .mobile-filter-sidebar {
  transform: translateX(0);
}

.filter-header {
  border-bottom: 1px solid #e9ecef;
}

.filter-body {
  flex: 1;
  overflow-y: auto;
}

.filter-footer {
  border-top: 1px solid #e9ecef;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .product-image {
    height: 180px !important;
  }
  
  .product-card .card-body {
    padding: 15px;
  }
  
  .product-name {
    font-size: 14px;
  }
  
  .product-description {
    font-size: 12px;
    -webkit-line-clamp: 1;
  }
  
  .product-price .current-price {
    font-size: 1rem;
  }
  
  .toolbar-left span {
    font-size: 13px;
  }
  
  /* 工具栏响应式优化 */
  .product-toolbar {
    flex-direction: column;
    align-items: stretch !important;
    gap: 15px;
  }
  
  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }
  
  .toolbar-right .btn-group,
  .toolbar-right .form-select {
    margin: 0 5px;
  }
  
  .product-list-item .product-image {
    height: 120px !important;
  }
}

@media (max-width: 576px) {
  .container {
    padding: 0 10px;
  }
  
  .product-card {
    margin-bottom: 15px;
  }
  
  .mobile-filter-sidebar {
    width: 280px;
  }
}
</style> 